package com.shi.shiro.jackson;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.core.Ordered;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

@Component
public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer, Ordered {

    private final String DATE_TIME_FORMAT="YYYY-MM-dd HH:mm:ss";
    private final String DATE_FORMAT="YYYY-MM-dd";

    @Override
    public void customize(Jackson2ObjectMapperBuilder builder) {
        // 配置序列化规则
        HashMap<Class<?>, JsonSerializer<?>> serializerHashMap=new HashMap<>();
        serializerHashMap.put(Long.class, ToStringSerializer.instance);
        serializerHashMap.put(BigInteger.class,ToStringSerializer.instance);
        serializerHashMap.put(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        serializerHashMap.put(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));

        // 配置反序列化规则
        HashMap<Class<?>, JsonDeserializer<?>> deserializerHashMap=new HashMap<>();
        deserializerHashMap.put(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        deserializerHashMap.put(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));

        // 添加规则
        builder.serializersByType(serializerHashMap);
        builder.deserializersByType(deserializerHashMap);
        builder.serializationInclusion(JsonInclude.Include.ALWAYS);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
